﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Mipic.Infrastructure.Converters
{
    public class BitmapToImageSourceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || !(value is Bitmap))
            {
                return null;
            }

            Bitmap bitmap = value as Bitmap;
            MemoryStream ms = new MemoryStream();

            ImageFormat format = ImageFormat.Png;
            //if (bitmap.RawFormat.Equals(ImageFormat.Png))
            //{
            //    format = ImageFormat.Png;
            //}
            //if (bitmap.RawFormat.Equals(ImageFormat.Jpeg))
            //{
            //    format = ImageFormat.Jpeg;
            //}

            if (format == null)
            {
                return null;
            }

            bitmap.Save(ms, format);

            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = ms;
            bi.EndInit();

            return bi;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}
